<template>
    <view class="main">
        <view class="user-box">
            <view class="user" v-if="isLogin" @click="toUpdate">
                <view class="avatar">
                    <image :src="userInfo?.avatar ? userInfo.avatar : '/static/appLogo.jpeg'" mode="scaleToFill" />
                </view>
                <view class="userName">{{ maskPhoneNumber(userInfo?.userName) ? maskPhoneNumber(userInfo?.userName) :
                    'user' }}</view>
            </view>
            <view class="c-login" v-else @click="handleLogin">点击登录</view>
        </view>
        <view class="car">
            <view v-if="!carList.length">
                <view class="car-top">
                    <view class="car-left" style="font-size: 30rpx;">暂无爱车</view>
                    <view class="add" @click="bindCar">
                        <wd-icon name="add-circle1" size="22px" color="#55946d"></wd-icon>
                    </view>
                </view>
                <view class="car-bottom">
                    <view class="tip">绑定车辆后，才能使用换电服务</view>
                </view>
            </view>
            <view v-else class="bind">
                <view class="tip my">
                    <view class="my">
                        <view>我的爱车</view>
                        <!-- <view class="add" @click="bindCar">
                            <wd-icon name="add-circle1" size="22px" color="#55946d"></wd-icon>
                        </view> -->
                    </view>
                </view>
                <view class="info" v-for="(item, index) in carList" :key="index">
                    <view>{{ item.model }}-{{
                        item.licensePlateNumber }}</view>
                    <view class="jb-box" @click="unBindCar(item.licensePlateNumber)">
                        <view class="jb">解绑</view>
                    </view>
                </view>

            </view>
        </view>
        <view class="option">
            <view v-for="(item, index) in optionList" :key="index">
                <button v-if="item.show" class="custom-btn" :open-type="item.isKf ? 'contact' : ''"
                    hover-class="button-hover" @click="clickItem(item)">
                    <view>{{ item.title }}</view>
                    <wd-icon :name="item.icon" color="#55946d" />
                </button>
            </view>
        </view>
    </view>
</template>
<script setup>
import { ref } from 'vue';
import { onLoad, onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { userDetail, carBindList, carUnBind } from '@/api/apiList'

const shareConf = ref({
    title: '云鹰换电',
    path: '/pages/mine/mineIndex',
})

onShareAppMessage(() => {
    return shareConf.value
})

onShareTimeline(() => {
    return shareConf.value
})

/**
 * 手机号码脱敏处理
 * @param {string} phone 手机号码字符串
 * @returns {string} 脱敏后的手机号码
 */
function maskPhoneNumber(phone) {
    try {
        // 取前3位和后4位，中间用*填充
        phone = String(phone)
        const prefix = phone.substring(0, 3);
        const suffix = phone.substring(phone.length - 4);
        const masked = prefix + '****' + suffix;
        return masked;
    } catch (error) {
        console.log(error, 'error')
    }
}

const unBindCar = async (licensePlateNumber) => {
    uni.showModal({
        title: '解绑车辆',
        content: '确定解绑车牌号为 ' + licensePlateNumber + ' 的车辆吗',
        success: async (res) => {
            if (res.confirm) {
                const res = await carUnBind({ licensePlateNumber })
                if (res.code == 200) {
                    uni.showToast({
                        title: '解绑成功',
                        icon: 'none'
                    })
                    await getUserDetail()
                    getCarList()
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            }
        }
    })
}

const getStorageToken = () => {
    const token = uni.getStorageSync('token')
    isLogin.value = token ? true : false
    setOption()
    optionList.value[optionList.value.length - 1].show = isLogin.value ? true : false
}

const carList = ref([])
const getCarList = async () => {
    const res = await carBindList()
    if (res.code == 200) {
        console.log(res, 'res')
        carList.value = res.data
        carList.value.length ? uni.setStorageSync('bind', 1) : uni.setStorageSync('bind', 0)
    }
}

onShow(async () => {
    getStorageToken()
    await getUserDetail()
    await getCarList()
})

// 获取用户详情
const userInfo = ref({})
const getUserDetail = async () => {
    const res = await userDetail()
    if (res.code == 200) {
        userInfo.value = res.data
        uni.setStorageSync('userInfo', JSON.stringify(res.data))
        isBandCar.value = userInfo.value?.isVehicle == 1 ? true : false
    }
}

const toUpdate = () => {
    uni.navigateTo({
        url: '/pages/mine/updateUserInfo'
    })
}

const isLogin = ref(true)
const isBandCar = ref(false)
const clickItem = (item) => {
    if (item.isKf) return;
    // 处理未登录情况
    if (!isLogin.value) {
        // 需要登录但未登录，跳转登录页
        if (item.login !== 'no') {
            return uni.navigateTo({ url: '/pages/login/login' });
        }
        // 不需要登录的页面直接跳转
        if (item.path) {
            return uni.navigateTo({ url: item.path });
        }
    }
    // 已登录情况
    else {
        // 有路径则跳转
        if (item.path) {
            if (item.type == 'order') {
                subscribe(() => {
                    uni.navigateTo({
                        url: item.path
                    })
                })
                // if (uni.getStorageSync('isDing') == 1) {
                //     uni.navigateTo({ url: item.path });
                // } else {
                //     subscribe(() => {
                //         uni.navigateTo({
                //             url: item.path
                //         })
                //     })
                // }
            } else {
                uni.navigateTo({ url: item.path });
            }
        }
    }
    // 处理退出登录（无论是否已跳转）
    if (item.isLogout) {
        handleLogout();
    }
}


const subscribe = (callBack) => {
    let tId = 'ADh3czKrR8BCl-xU1v5M7HEvs-2s57jISDSEfcyCAOk'
    uni.requestSubscribeMessage({
        tmplIds: [tId],
        success(res) {
            if (res[tId] == 'accept') {
                uni.setStorageSync('isDing', 1)
            } else {
                uni.setStorageSync('isDing', 2)
            }
        },
        fail: res => {
        },
        complete: res => {
            callBack()
        }
    })
}
const bindCar = () => {
    if (isLogin.value) {
        subscribe(() => {
            uni.navigateTo({
                url: '/pages/mine/bindCar'
            })
        })
    } else {
        uni.navigateTo({
            url: '/pages/login/login'
        })
    }
}

const handleLogout = () => {
    uni.showModal({
        title: '退出登录',
        content: '确定退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                uni.showLoading({
                    title: '正在退出···'
                })
                uni.removeStorageSync('token')
                uni.removeStorageSync('userInfo')

                isBandCar.value = false
                getStorageToken()
                uni.hideLoading()
                uni.switchTab({
                    url: '/pages/index/index'
                })
            }
        }
    })
}

const handleLogin = () => {
    uni.navigateTo({
        url: '/pages/login/login'
    })
}

const optionList = ref([])
const setOption = () => {
    optionList.value = [
        {
            title: '我的订单',
            path: '/pages/mine/myOrder',
            icon: 'arrow-right',
            login: 'yes',
            type: 'order',
            show: true,
        },
        {
            title: '联系客服',
            path: '',
            icon: 'arrow-right',
            isKf: true,
            show: true,
        }, {
            title: '用户反馈',
            path: '/pages/mine/feedback',
            icon: 'arrow-right',
            login: 'yes',
            show: true,
        },
        //  {
        //     title: '反馈历史',
        //     path: '/pages/mine/feedbackHistory',
        //     icon: 'arrow-right',
        //     login: 'yes',
        //     show: true
        // }, 
        {
            title: '用户服务协议',
            path: '/pages/login/agreement?type=user',
            icon: 'arrow-right',
            login: 'no',
            show: true
        }, {
            title: '隐私政策',
            path: '/pages/login/agreement?type=privacy',
            icon: 'arrow-right',
            login: 'no',
            show: true
        }, {
            title: '退出登录',
            path: '',
            icon: 'logout',
            isLogout: true,
            show: true
        }]
}
</script>

<style lang="scss" scoped>
.main {
    padding: 5rpx;

    .user-box {
        padding: 20rpx;

        .c-login {
            font-size: 18px;
            font-weight: 700;
        }

        .user {
            display: flex;
            align-items: center;

            .avatar {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                margin-right: 10px;

                image {
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }
            }

            .userName {
                font-size: 16px;
            }
        }
    }

    .car {
        padding: 20rpx;
        border: 1rpx solid #eee;
        margin-bottom: 5rpx;
        border-radius: 10rpx;

        .bind {

            .info {
                margin-top: 20rpx;
                font-weight: 900;
                font-size: 30rpx;
                color: #e4ab8a;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }

        .car-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .car-bottom {
            margin-top: 20rpx;

            .tip {
                font-weight: 900;
                font-size: 30rpx;
                color: #e4ab8a;
            }
        }
    }
}

/* 方法1：全局重置所有按钮样式 */
button {
    margin: 0;
    padding: 0;
    line-height: 1;
    background-color: transparent;
    border: none;
}

button::after {
    border: none;
}

.my {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}


.jb-box {
    display: flex;
    justify-content: flex-end;

    .jb {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 30rpx;
        color: #649270;
        border: 1rpx solid #649270;
        padding: 5rpx 10rpx;
        border-radius: 15rpx;
    }
}

/* 方法2：单独自定义按钮样式 */
// .custom-btn
.custom-btn {
    margin: 0;
    line-height: normal;
    background-color: transparent;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 20rpx;
    font-size: 30rpx;
    border-bottom: 1rpx solid #eee;
    border-left: 1rpx solid #eee;
    border-right: 1rpx solid #eee;
    border-radius: 10rpx;
    font-size: 30rpx;
}

.custom-btn::after {
    border: none;
}
</style>
